<!--
 * @Author: Christion.Young
 * @Date: 2020-11-24 16:50:45
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2021-01-06 17:38:32
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2021-01-04 15:56:50
 * @Description: file content
-->
<template>
    <!--  -->
    <div>
        <el-row class="caliberHierarchy container"
                :gutter="10">
            <!-- 左侧树 -->
            <el-col :span="6"
                    style="padding-top:10px;padding:0 10px">
                <vp-tree vp-title="所有数据表"
                         class="ie-tree-style"
                         :vp-header="{show:true,text:'数据表',search:true,name:'tableNameCn'}"
                         :data="treeData"
                         :props="defaultProps"
                         @node-click="handleNodeClick"
                         default-expand-all
                         check-strictly
                         ref="treeDataRef"
                         node-key="tableNameEn"
                         :expand-on-click-node="false"
                         check-on-click-node></vp-tree>
            </el-col>
            <!-- 右侧表  -->
            <el-col :span="18"
                    class="content-left ie-box-toLong">
                <el-tabs v-model="editableTabsValue"
                         type="card"
                         closable
                         @tab-click="clickTab"
                         @tab-remove="removeTab">
                    <el-tab-pane v-for="item in editableTabs"
                                 :key="item.name"
                                 :label="item.title"
                                 :name="item.name">
                    </el-tab-pane>
                    <el-row class="actionBarBox">
                        <div class="actionBar">
                            <div class="actionBarTit">查询模板：</div>
                            <el-select v-model="templateValue"
                                       @change="phyTableQueryListChange"
                                       placeholder="请选择"
                                       style="margin-right:10px;">
                                <el-option v-for="item in templateOptions"
                                           :key="item.searchtemplateId"
                                           :label="item.searchtemplateName"
                                           :value="item.searchtemplateId">
                                </el-option>
                            </el-select>
                            <el-button @click="addedBtn">新增</el-button>
                            <el-button @click="compileBtn">编辑</el-button>
                            <el-button @click="deleteBtn">删除</el-button>
                            <el-button @click="setDefault">设为默认</el-button>
                            <div class="checkedChineseEnglishBox">
                                <el-checkbox v-model="checkedChineseEnglish">英文显示</el-checkbox>
                            </div>
                        </div>
                    </el-row>
                    <el-row class="searchBarBox">
                        <el-col v-if="searchTerms.length==0?true:false"
                                :span="24"
                                class="searchBarBoxNull">暂无查询项</el-col>
                        <el-form v-if="searchTerms.length==0?false:true"
                                 ref="searchTermsDispose"
                                 label-width="140px"
                                 label-position="left">
                            <el-row class="dynamicItem">
                                <el-col v-for="(item, index) in searchTermsDispose"
                                        :key="index"
                                        :span="12"
                                        >
                                    <el-form-item :label="item.label+'：'">
                                        <searchTem v-model="item.value"
                                                   ref="searchTem"
                                                   :treeType="item.treeType"
                                                   :seachType="item.type" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="24"
                                        style="display: flex;justify-content: center;">
                                    <el-button @click="searchSubmit">查询</el-button>
                                    <el-button @click="searchReset">重置</el-button>

                                </el-col>
                            </el-row>
                        </el-form>
                    </el-row>
                    <el-row>
                        <el-col :span="24"
                                style="display: flex;margin-bottom: 10px;">
                            <el-button @click="exportFiles">导出</el-button>
                        </el-col>
                    </el-row>
                    <el-table ref="tableDataRef"
                              :data="tableData"
                              style="width: 100%">
                             
                              >
                        <el-table-column v-for="(item ,index) in this.headData"
                                         show-overflow-tooltip
                                         :key="index"
                                         :prop="item.columnEn.toUpperCase()"
                                         :label="!checkedChineseEnglish?item.columnCn:item.columnEn.toUpperCase()">
                        </el-table-column>
                    </el-table>
                    <pagination @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                @refresh="searchFunc"
                                :current-page="searchPaging.page"
                                :page-size="searchPaging.size"
                                :total="total"></pagination>
                </el-tabs>
            </el-col>
        </el-row>
        <el-dialog v-dialogDrag
                   title="编辑查询模板"
                   :visible.sync="addOrEdit"
                   width="800px">
            <el-row>
                <el-col :span="24"
                        class="transferBox">
                    <el-form :model="saveForm"
                             ref="saveFormRef"
                             label-width="100px"
                             label-position="left"
                             :rules="saveFormRules">
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="模板名称："
                                              prop="inputName">
                                    <el-input v-model="saveForm.inputName"
                                              maxlength="10"
                                              style="width:400px;"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-col>
                <el-col :span="24"
                        class="transferBox">
                    <el-transfer :titles="['查询字段', '新增查询']"
                                 filterable
                                 filter-placeholder="模糊查询"
                                 v-model="rightValue"
                                 :filter-method="filterMethod"
                                 :data="leftData">
                    </el-transfer>
                </el-col>
            </el-row>
            <div slot="footer"
                 class="dialog-footer">
                <el-button @click="saveFunc">确 定</el-button>
                <el-button @click="addOrEdit = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import searchTem from './searchTem'
import { caPubDriver, publicManage_dat } from '@/api/index'
export default {
    components: {
        searchTem,
    },
    data() {
        //  定义穿梭框-左侧数据
        return {
            //  TAB值
            editableTabsValue: 'HOME',
            //  TAB信息
            editableTabs: [],
            //  左侧####################################################################################
            //  左侧-数据表列表-选中值
            tabsValue: {},
            //  左侧-数据表列表
            treeData: [],
            //  左侧-查询数据
            filterText: '',
            //  左侧-默认展示
            defaultProps: {
                children: 'children',
                label: 'tableNameCn',
            },
            //  右侧####################################################################################
            checkedChineseEnglish: false,
            //  右侧-列表-数据
            tableData: [],
            //  右侧-列表-表头
            headData: [],
            //  请求模板下拉
            templateOptions: [],
            //  请求模板下拉值
            templateValue: '',
            //  搜索项数据
            searchTerms: [],
            //  搜索项数据-处理
            searchTermsDispose: [],
            //  整理出来的搜索数据请求参数
            searchParameter: {},
            //  分页单独数据存储
            searchPaging: {
                page: 1,
                size: 15,
            },
            //  整理出来的搜索数据请求参数
            total: 10,
            //  弹窗####################################################################################
            addOrEdit: false,
            //  穿梭框-左侧-值
            leftData: [],
            //  穿梭框-右侧-值
            rightValue: [],
            //  穿梭框-顶部-名称
            saveForm: {
                inputName: '',
            },
            saveFormRules: {
                inputName: [
                    {
                        required: true,
                        message: '该输入项为必输项',
                        trigger: 'blur',
                    },
                    {
                        pattern: /^\s*(\S+)\s*$/,
                        message: '不允许输入空格',
                        trigger: 'blur',
                    },
                ],
            },
            //  按钮类型
            buttomType: '',
        }
    },

    mounted() {
        this.getTreeData()
    },
    computed: {},
    watch: {},
    methods: {
        exportFiles() {
            this.searchParameter.objectId = this.tabsValue.tableNameEn
            let params = {
                clomns: this.headData,
                objectId: this.tabsValue.tableNameEn,
                data: this.searchParameter,
                language: this.checkedChineseEnglish,
            }
            caPubDriver.exportSearchTable(params).then((response) => {
                if (response) {
                    var filename = this.tabsValue.tableNameEn + '.xlsx'
                    var blob = new Blob([response.data], {
                        type: 'application/vnd.ms-excels;charset=utf-8',
                    })
                    if (window.navigator.msSaveOrOpenBlob) {
                        navigator.msSaveBlob(blob, filename)
                    } else {
                        var downloadElement = document.createElement('a')
                        var href = window.URL.createObjectURL(blob) //创建下载的链接
                        downloadElement.href = href
                        downloadElement.download = filename //下载后文件名
                        document.body.appendChild(downloadElement)
                        downloadElement.click() //点击下载
                        document.body.removeChild(downloadElement) //下载完成移除元素
                        window.URL.revokeObjectURL(href) //释放掉blob对象
                    }
                } else {
                    this.$message.error(response.message || '获取失败')
                }
            })
        },
        //  TAB-删除
        removeTab(targetName) {
            if (this.editableTabs.length > 1) {
                let tabs = this.editableTabs
                let activeName = this.editableTabsValue
                if (activeName === targetName) {
                    tabs.forEach((tab, index) => {
                        if (tab.name === targetName) {
                            let nextTab = tabs[index + 1] || tabs[index - 1]
                            if (nextTab) {
                                activeName = nextTab.name
                            }
                        }
                    })
                }
                this.editableTabsValue = activeName
                this.editableTabs = tabs.filter(
                    (tab) => tab.name !== targetName
                )
                if (this.editableTabs.length != 0) {
                    let obj = {
                        label: this.editableTabs[this.editableTabs.length-1].title,
                    }
                    this.clickTab(obj)
                }
            }
        },
        //  TAB-新增
        addTab() {
            let filterArr = []
            filterArr = this.editableTabs.filter((item) => {
                return item.name == this.tabsValue.tableNameEn
            })
            if (filterArr.length == 0) {
                this.editableTabs.push({
                    title: this.tabsValue.tableNameCn,
                    name: this.tabsValue.tableNameEn,
                    tabsData: this.tabsValue,
                })
            }
            this.editableTabsValue = this.tabsValue.tableNameEn
        },
        //  TAB-点击
        clickTab(val) {
            let arr = []
            arr = this.editableTabs.filter((item) => {
                return item.title == val.label
            })
            this.tabsValue = arr[0].tabsData
            this.searchFunc()
            this.phyTableQueryList()
            this.searchPaging.page = 1
            this.searchPaging.size = 15
        },
        //  左侧####################################################################################
        //  左侧-列表-获取-选中默认值
        getTreeData() {
            publicManage_dat.queryFundTableList().then((res) => {
                if (res.code === 200) {
                    this.treeData = res.datas
                    this.$nextTick(() => {
                        this.handleNodeClick(this.treeData[0])
                    })
                }
            })
        },
        //  左侧-列表-模糊查询
        filterTree() {
            this.$refs.treeDataRef.filter(this.filterText)
        },
        //  左侧-列表-模糊查询
        filterNode(value, data) {
            if (!value) return true
            return data.tableNameCn.indexOf(value) !== -1
        },
        //  左侧-列表-点击列表项
        handleNodeClick(val) {
            this.tabsValue = val
            this.searchFunc()
            this.phyTableQueryList()
            this.addTab()
            this.searchPaging.page = 1
            this.searchPaging.size = 15
        },
        //  右侧####################################################################################
        //  右侧-顶部-回显-请求模板下拉/值
        phyTableQueryList() {
            caPubDriver
                .phyTableQueryList({
                    objectId: this.tabsValue.tableNameEn,
                })
                .then((res) => {
                    if (res.code === 200) {
                        this.templateOptions = res.datas
                        //  判断下拉模板中是否右默认值
                        let arr = []
                        arr = res.datas.filter((item) => {
                            return item.isDefault == '1'
                        })
                        if (arr.length != 0) {
                            this.templateValue = arr[0].searchtemplateId
                            //  根据默认项请求搜索项数据
                            this.queryInputsByTempId(this.templateValue)
                        } else {
                            this.templateValue = ''
                            this.searchTerms = []
                        }
                    }
                })
        },
        //  右侧-顶部-请求模板下拉触发
        phyTableQueryListChange(val) {
            this.queryInputsByTempId(val)
        },
        //  右侧-顶部-请求模板下拉数据
        getPhyTableQueryList() {
            caPubDriver
                .phyTableQueryList({
                    objectId: this.tabsValue.tableNameEn,
                })
                .then((res) => {
                    if (res.code === 200) {
                        this.templateOptions = res.datas
                    }
                })
            if (this.templateValue != '') {
                this.queryInputsByTempId(this.templateValue)
            }
        },
        //  右侧-顶部-新增
        addedBtn() {
            this.buttomType = '1'
            this.rightValue = []
            this.saveForm.inputName = ''
            this.generateData()
            this.addOrEdit = true
        },
        //  右侧-顶部-编辑
        compileBtn() {
            if (this.templateValue != '') {
                this.buttomType = '2'
                this.generateData()
                this.getCompileBtnData()
                this.addOrEdit = true
            } else {
                this.$message.warning('请选择数据进行编辑')
            }
        },
        //  右侧-顶部-编辑-回显
        getCompileBtnData() {
            //  穿梭框-右侧-值
            this.rightValue = []
            for (let index = 0; index < this.searchTerms.length; index++) {
                const element = this.searchTerms[index]
                this.rightValue.push(element.columnEn)
            }
            //  穿梭框-顶部-名称
            let arr = []
            arr = this.templateOptions.filter((item) => {
                return item.searchtemplateId == this.templateValue
            })
            this.saveForm.inputName = arr[0].searchtemplateName
        },
        //  右侧-顶部-删除
        deleteBtn() {
            if (this.templateValue != '') {
                this.$confirm('你确定要删除选中的数据吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                })
                    .then(() => {
                        caPubDriver
                            .removeSearchTemplate({ ids: [this.templateValue] })
                            .then((res) => {
                                if (res.code == 200) {
                                    this.$message.success('删除成功')
                                    this.getPhyTableQueryList()
                                    this.templateValue = ''
                                    this.searchTerms = []
                                    this.searchTermsDispose = []
                                }
                            })
                    })
                    .catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除',
                        })
                    })
            } else {
                return this.$message.warning('请选择数据进行删除')
            }
        },
        //  右侧-顶部-设为默认
        setDefault() {
            if (this.templateValue != '') {
                caPubDriver
                    .updateDefault({
                        objectId: this.tabsValue.tableNameEn,
                        searchtemplateId: this.templateValue,
                    })
                    .then((res) => {
                        if (res.code == 200) {
                            this.$message.success('设为默认成功')
                        }
                    })
            } else {
                this.$message.warning('请选择数据进行编辑')
            }
        },
        //  右侧-搜索项-请求
        queryInputsByTempId(val) {
            caPubDriver
                .queryInputsByTempId({
                    objectId: this.tabsValue.tableNameEn,
                    searchtemplateId: val,
                })
                .then((res) => {
                    if (res.code == 200) {
                        this.searchTerms = res.datas
                        const filter = this.searchTerms.filter(
                           (item)=>item.dataType == 'DATE'
                       )
                       for(let i=0;i<this.searchTerms.length;i++){
                           if(this.searchTerms[i].dataType == 'DATE'){
                               this.searchTerms.splice(i,1)
                           }
                       }
                       if(filter.length){
                           this.searchTerms.push(filter[0])
                       }
                        this.getSearchParameter()
                    }
                })
        },

        //  右侧-搜索项-数据处理
        getSearchParameter() {
            this.searchTermsDispose = []
            this.searchParameter = {}
            //  请求搜索项数据数据处理
            for (let index = 0; index < this.searchTerms.length; index++) {
                let obj = {
                    type: '',
                    label: '',
                    field: '',
                    value: '',
                    treeType: '',
                }
                const element = this.searchTerms[index]
                console.log(element, 'canshu')
                obj.label = element.columnCn
                obj.field = element.columnEn.toUpperCase()
                this.searchParameter[element.columnEn.toUpperCase()] = ''
                if (element.relatedDimensionCode != '') {
                    obj.type = 'TREE'
                    if (element.relatedDimensionCode) {
                        obj.treeType = element.relatedDimensionCode
                    } else {
                        obj.treeType = ''
                    }
                } else {
                    if (element.dataType == 'DATE') {
                        obj.type = 'DATE'
                    } else {
                        obj.type = 'INPUT'
                    }
                }
                this.searchTermsDispose.push(obj)
            }
            this.searchTemReset()
        },
        //  请求参数-数据处理
        searchParameterFilter() {
            //  整理出来的搜索数据请求参数
            for (
                let index = 0;
                index < this.searchTermsDispose.length;
                index++
            ) {
                const element = this.searchTermsDispose[index]
                for (let k in this.searchParameter) {
                    if (k == element.field) {
                        this.searchParameter[k] = element.value
                    }
                }
            }
            console.log(this.searchTermsDispose, '请求的参数1')
            console.log(this.searchParameter, '请求的参数2')
        },
        //  右侧-搜索-头部-列表
        searchFunc() {
            this.searchParameterFilter()
            //  请求头部数据
            publicManage_dat
                .fundToolColumnQueryListCa({
                    tableNameEn: this.tabsValue.tableNameEn,
                })
                .then((res) => {
                    if (res.code == 200) {
                        this.headData = res.datas
                    }
                })
            //  请求列表数据
            this.searchParameter.objectId = this.tabsValue.tableNameEn
            this.searchParameter.size = this.searchPaging.size
            this.searchParameter.page = this.searchPaging.page
            caPubDriver.queryPhyData(this.searchParameter).then((res) => {
                console.log(this.searchParameter, '传递的参数')
                if (res.code == 200) {
                    this.tableData = res.datas.rows
                    this.total = res.datas.total
                }
            })
        },
        //  搜索-提交
        searchSubmit() {
            this.searchFunc()
        },
        //  搜索-重置
        searchReset() {
            this.searchTemReset()
        },
        //  搜索-组件内部数据重置
        searchTemReset() {
            for (var k in this.searchParameter) {
                this.searchParameter[k] = ''
            }
            if (this.searchTermsDispose.length != 0) {
                for (
                    let index = 0;
                    index < this.searchTermsDispose.length;
                    index++
                ) {
                    if (
                        this.$refs.searchTermsDispose &&
                        this.searchTermsDispose[index]
                    ) {
                        this.searchTermsDispose[index].value = ''
                    }
                    if (this.$refs.searchTem && this.$refs.searchTem[index]) {
                        this.$refs.searchTem[index].$emit('bridge')
                    }
                }
            }
            console.log(this.searchTermsDispose, '查询面板的参数1')
            console.log(this.searchParameter, '查询面板的参数2')
        },
        //  分页-搜索
        handleSizeChange(val) {
            this.searchPaging.size = val
            console.log(val, '大小')
            this.searchFunc()
        },
        //  分页-搜索
        handleCurrentChange(val) {
            this.searchPaging.page = val
            console.log(this.searchParameter.page, '页数')
            this.searchFunc()
        },
        //  弹窗####################################################################################
        //  弹窗-保存
        saveFunc() {
            if (this.rightValue.length > 10) {
                this.$message.warning(
                    '最多支持10个查询字段，请确认查询字段数量。'
                )
            } else if (this.rightValue.length < 1) {
                this.$message.warning('查询字段为必选项，请选择查询字段。')
            } else {
                this.$refs.saveFormRef.validate((valid) => {
                    if (valid) {
                        console.log('+')
                        let searchItems = ''
                        let searchtemplateId = ''
                        for (let i = 0; i < this.rightValue.length; i++) {
                            if (i != 0) {
                                searchItems += '@@@'
                                searchItems += this.rightValue[i]
                            } else {
                                searchItems += this.rightValue[i]
                            }
                        }
                        if (this.buttomType == '1') {
                            searchtemplateId = ''
                            caPubDriver
                                .checkSearchTemplateName({
                                    objectId: this.tabsValue.tableNameEn,
                                    searchtemplateName: this.saveForm.inputName,
                                })
                                .then((res) => {
                                    if (
                                        res.code == 200 &&
                                        res.success == true
                                    ) {
                                        caPubDriver
                                            .saveSearchTemplate({
                                                objectId: this.tabsValue
                                                    .tableNameEn,
                                                searchItems: searchItems,
                                                searchtemplateId: searchtemplateId,
                                                searchtemplateName: this
                                                    .saveForm.inputName,
                                            })
                                            .then((res) => {
                                                if (res.code == 200) {
                                                    this.$message.success({
                                                        showClose: true,
                                                        message: '保存成功',
                                                        duration: '1000',
                                                    })
                                                    this.addOrEdit = false
                                                    this.getPhyTableQueryList()
                                                }
                                            })
                                    } else {
                                        this.$message.warning('名称重复')
                                    }
                                })
                        } else {
                            searchtemplateId = this.templateValue
                            caPubDriver
                                .saveSearchTemplate({
                                    objectId: this.tabsValue.tableNameEn,
                                    searchItems: searchItems,
                                    searchtemplateId: searchtemplateId,
                                    searchtemplateName: this.saveForm.inputName,
                                })
                                .then((res) => {
                                    if (res.code == 200) {
                                        this.$message.success({
                                            showClose: true,
                                            message: '保存成功',
                                            duration: '1000',
                                        })
                                        this.addOrEdit = false
                                        this.getPhyTableQueryList()
                                    }
                                })
                        }
                    }
                })
            }
        },
        //  穿梭框-数据处理
        generateData() {
            this.leftData = []
            this.headData.forEach((item) => {
                this.leftData.push({
                    label: item.columnCn,
                    key: item.columnEn,
                    dataType: item.dataType,
                })
            })
        },
        //  穿梭框-过滤-模糊查询
        filterMethod(query, item) {
            return item.label.indexOf(query) > -1
        },
    },
}
</script>

<style lang="scss" scoped>
.top-title {
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #000000;
    line-height: 20px;
    vertical-align: middle;
    margin-top: 9px;
}
.vertical-bar {
    line-height: 20px;
    font-weight: 500px;
}
.actionBarBox {
    background: #eeeeee;
    padding: 10px 0 10px 10px;
    .actionBar {
        display: flex;
        width: 100%;
        align-items: center;
    }
    .actionBarTit {
        font-size: 14px;
        font-weight: 900;
    }
}
.searchBarBox {
    padding: 10px 10px 10px 0;
    .searchBarBoxNull {
        text-align: center;
        font-size: 14px;
        color: red;
        height: 40px;
        line-height: 40px;
    }
}
.checkedChineseEnglishBox {
    position: absolute;
    right: 16px;
    top: 16px;
}
.transferLabel {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 100px;
    font-weight: 900;
    font-size: 14px;
}
.transferBox {
    display: flex;
    justify-content: center;
    margin: 20px 0px 20px 0px;
}
.dynamicItem {
    max-height: 100px;
    overflow-y: auto;
}
</style>